import React, { useState } from 'react';
import { Form, Input, Select, Button, message } from 'antd';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
import CryptoJS from "crypto-js";

const { Option } = Select;

const AddUser = () => {
    const [form] = Form.useForm();
    const navigate = useNavigate();
    const [loading, setLoading] = useState(false);

    const onFinish = async (values) => {
        setLoading(true);
        // 我的密钥
        const secretKey = import.meta.env.VITE_APP_SECRET_KEY; // 从 .env 文件中获取密钥

        // 对密码进行AES加密
        const keyBytes = CryptoJS.enc.Base64.parse(secretKey);
        const encryptedPassword = CryptoJS.AES.encrypt(values.password, keyBytes, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 }).toString();

        try {
            // 发送请求到后端
            const response = await axios.post('http://localhost:8080/api/users/adduser', {
                userName: values.username,
                userPassword: encryptedPassword,
                nickname: values.nickname || null,
                gender: values.gender || null,
                age: values.age || null,
            });

            const responseResult = response.data;
            if (response.status === 200 && responseResult.code === 200) {
                message.success('用户添加成功');
                form.resetFields(); // 重置表单
                navigate('/admin/user'); // 跳转到用户列表页面
            } else {
                message.error(responseResult.message || '用户添加失败，请检查输入');
            }
        } catch (error) {
            console.error('用户添加失败：', error);
            message.error(error.response?.data?.message || '用户添加失败，请检查输入');
        } finally {
            setLoading(false);
        }
    };

    const handleReturn = () => {
        navigate(-1); // 返回上一个页面
    };

    return (
        <div style={{ maxWidth: '500px', margin: 'auto' }}>
            <h2>添加用户</h2>
            <Form
                form={form}
                name="add_user"
                onFinish={onFinish}
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 16 }}
                style={{ width: '100%' }}
            >
                <Form.Item
                    label="用户名"
                    name="username"
                    rules={[
                        { required: true, message: '请输入用户名!' },
                        { max: 20, message: '用户名长度不能超过20个字符' },
                    ]}
                >
                    <Input style={{ width: '100%' }} />
                </Form.Item>

                <Form.Item
                    label="密码"
                    name="password"
                    rules={[
                        { required: true, message: '请输入密码!' },
                        { min: 8, message: '密码长度至少为8个字符' },
                        {
                            pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/,
                            message: '密码必须包含至少一个小写字母、一个大写字母和一个数字',
                        },
                    ]}
                >
                    <Input.Password style={{ width: '100%' }} />
                </Form.Item>

                <Form.Item
                    label="昵称"
                    name="nickname"
                    rules={[{ max: 20, message: '昵称长度不能超过20个字符' }]}
                >
                    <Input style={{ width: '100%' }} />
                </Form.Item>

                <Form.Item label="性别" name="gender">
                    <Select placeholder="请选择性别" style={{ width: '100%' }}>
                        <Option value="男">男</Option>
                        <Option value="女">女</Option>
                    </Select>
                </Form.Item>

                <Form.Item
                    label="年龄"
                    name="age"
                    rules={[
                        {
                            type: 'number',
                            transform: (value) => value && parseFloat(value),
                            min: 0,
                            max: 150,
                            message: '年龄范围为0到150',
                        },
                    ]}
                >
                    <Input style={{ width: '100%' }} />
                </Form.Item>

                <Form.Item wrapperCol={{ offset: 4, span: 16 }}>
                    <Button
                        type="primary"
                        htmlType="submit"
                        loading={loading}
                        style={{ marginRight: '8px', width: '100px' }}
                    >
                        保存
                    </Button>
                    <Button onClick={handleReturn} style={{ width: '100px' }}>
                        返回
                    </Button>
                </Form.Item>
            </Form>
        </div>
    );
};

export default AddUser;